package com.tdam2011.grupo05.processor;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.tdam2011.grupo05.database.manager.DataManager;
import com.tdam2011.grupo05.entities.account.Account;
import com.tdam2011.grupo05.entities.contact.ContactWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb;
import com.tdam2011.grupo05.entities.message.MessageWeb.State;
import com.tdam2011.grupo05.entities.message.MessageWeb.Type;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;
import com.tdam2011.grupo05.services.constant.MessageConstant;
import com.tdam2011.grupo05.services.constant.ServiceResult;
import com.tdam2011.grupo05.utils.parser.XMLParser.Entry;
import com.tdam2011.grupo05.utils.parser.XMLParser.Message;
import com.tdam2011.grupo05.utils.preference.PreferencesHelper;

public class GetMessageProcessor implements Processor {

	public static final String THREAD_ID = "thread_id";
	public static final String MESSAGE = "message";
	public static final String THREAD = "thread";
	private final static String TAG = "GetMessageProcessor";
	private static int idRequest = 0;
	private final ResultReceiver mReceiver;
	private final DataManager mManager;
	private final SimpleDateFormat dateFormat;
	private final PreferencesHelper mHelper;
	private final Account mAccount;

	public GetMessageProcessor(DataManager dataManager, Account a,
			ResultReceiver receiver, PreferencesHelper helper) {
		mManager = dataManager;
		mAccount = a;
		mReceiver = receiver;
		mHelper = helper;
		dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss",
				Locale.getDefault());

	}

	@Override
	public StringEntity handleRequest() throws UnsupportedEncodingException {
		Log.i(TAG, "handleRequest");
		long lastPolling = mHelper.getLastSync();
		StringEntity se = new StringEntity("<action id=\"" + idRequest++
				+ "\" name=\"get-messages\">" + "<action-detail>"
				+ "<auth username=\"" + mAccount.getUsername() + "\" key=\""
				+ mAccount.getPassword() + "\">" + "</auth>"
				+ "<filter type=\"timestamp\">" + ""
				+ dateFormat.format(new Date(lastPolling)) + "" + "</filter>"
				+ "</action-detail>" + "</action>", HTTP.UTF_8);
		se.setContentType("text/xml");

		mHelper.updateLastSync(System.currentTimeMillis());
		mAccount.setLastSync(mHelper.getLastSync());
		mManager.updateAccount(mAccount);
		Log.d(TAG, "lastsync=" + dateFormat.format(new Date(lastPolling)));
		return se;
	}

	@Override
	public void handleResponse(Entry response, String requestAction) {
		Log.i(TAG, "handleResponse");
		MessageWeb m = null;
		ThreadWeb t = null;
		if (response != null) {
			Bundle data = new Bundle();
			if (response.getMessages() != null) {
				for (Message mes : response.getMessages()) {
					m = new MessageWeb();
					m.setText(mes.getMessage());
					try {
						m.setTimestamp(dateFormat.parse(mes.getTime()));
					} catch (ParseException e) {
						Log.e(TAG, "date error", e);
						m.setTimestamp(new Date(mHelper.getLastSync()));
					}
					m.setState(State.UNREAD);
					m.setType(Type.INCOMING);
					m.setResult(response.getType());
					t = getThread(mes.getFrom());
					m.setIdThread(t.getId());
					saveMessage(m);

					data.putString(MessageConstant.SENDER_MESSAGE,
							mes.getFrom());
					data.putString(THREAD, t.getName());
					data.putString(MESSAGE, m.getText());
					data.putLong(THREAD_ID, t.getId());
					mReceiver.send(ServiceResult.MESSAGES_GET_OK, data);

				}
			}

		} else {
			mReceiver.send(ServiceResult.MESSAGES_GET_FAIL, null);
		}

	}

	public void saveMessage(MessageWeb m) {
		long id = mManager.saveMessage(m);
		Log.d(TAG, "new message saved=" + id);
	}

	public ThreadWeb getThread(String contact) {
		// find open thread or create new one
		ContactWeb c = mManager.getContactWebByName(contact);

		if (c == null) {
			c = new ContactWeb();
			c.setIdPhone(-1);
			c.setIdContacto(-1);
			c.setName(contact);
			long id = mManager.saveContactWeb(c);
			c.setId(id);
		}

		ThreadWeb t = mManager.getThreadByContact(c.getId());
		if (t == null) {
			t = new ThreadWeb();
			t.setDate(new Date());
			t.setName(contact);
			t.setUser(c);
			t.setState(com.tdam2011.grupo05.entities.thread.ThreadWeb.State.HAVE_UNREAD);
			t.setIdAccount(mAccount.getId());
			long id = mManager.saveThread(t);
			t.setId(id);
		} else {
			t.setState(com.tdam2011.grupo05.entities.thread.ThreadWeb.State.HAVE_UNREAD);
			updateThread(t);
		}

		return t;
	}

	public void updateThread(ThreadWeb t) {
		mManager.updateThread(t);
	}

	@Override
	public void cancelRequest() {
	}

}
